//
//  MineViewController.m
//  TasteEnjoy
//
//  Created by XuRui on 16/4/19.
//  Copyright © 2016年 XuRui. All rights reserved.
//

#import "MineViewController.h"
#import <MessageUI/MessageUI.h>



@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource,  UINavigationControllerDelegate, UIImagePickerControllerDelegate,MFMailComposeViewControllerDelegate>

/**< 代理 */
@property (nonatomic, retain) BaseTableView *tableView;
@property (nonatomic, retain) BaseImageView *headerView;

@property (nonatomic, retain) BaseImageView *imgHeader; /**< 头像 */

@property (nonatomic, retain) NSString *imgPath; /**< 保存到沙盒的一个路径 */

@property (nonatomic, assign) CGFloat cache;/**< 缓存的数值 */

@property (nonatomic, assign) BOOL isSelected;
@end

@implementation MineViewController

#pragma mark - ------------ 内存管理 ---------------
- (void)dealloc
{
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
    
    [_tableView release];
    [_headerView release];
    [_imgHeader release];
    [_imgPath release];
    [super dealloc];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 
    self.navigationItem.title = @"设置";
    //扫一扫
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"sao"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(sao:)]autorelease];
    self.cache = 0;
    [self createTableView];
    [self crateHeaderView];
    

}


#pragma mark - ------------ 扫一扫 ---------------
- (void)sao:(UIBarButtonItem *)item
{
    Scan_VC *er = [[Scan_VC alloc]init];
    
    UINavigationController *erweima = [[UINavigationController alloc]initWithRootViewController:er];
    
    [self presentViewController:erweima animated:YES completion:nil];
    
    [er release];
    [erweima release];
}

#pragma mark - ------------ 创建头部视图 登录 ---------------
- (void)crateHeaderView
{

    self.headerView = [[BaseImageView alloc]initWithFrame:CGRectMake(0, -200, SCREEN_WIDTH, 200)];
    _headerView.image = [UIImage imageNamed:@"mine.jpg"];
    _headerView.userInteractionEnabled = YES;
    _headerView.contentMode = UIViewContentModeScaleAspectFill;
    _headerView.clipsToBounds = YES;
    [self.tableView addSubview:_headerView]; /**< 为了有深拉 */
    
    
    self.imgHeader = [[BaseImageView alloc]init];
    _imgHeader.backgroundColor = [UIColor redColor];
    [_headerView addSubview:_imgHeader];
    [_imgHeader mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.width.height.mas_equalTo(100);
        make.centerX.centerY.mas_equalTo(_headerView);
        
    }];
//    Frame:CGRectMake(0,0, 100, 100)];
//    _img.center = CGPointMake(self.view.center.x, self.view.center.y);
    _imgHeader.layer.cornerRadius = 50;
    _imgHeader.clipsToBounds = YES;
    _imgHeader.userInteractionEnabled = YES;
    _imgHeader.image = [UIImage imageNamed:@"mine.jpg"];
   
    //tap手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImg:)];
    [_imgHeader addGestureRecognizer:tap];
    
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //判断 下次在启动可以保存之前修改后的照片
    if ([userDefaults dataForKey:@"img"]) {
        [_imgHeader setImage:[UIImage imageWithData:[userDefaults dataForKey:@"img"]]];
    }
    
    [tap release];
    [_headerView release];
    [_imgHeader release];
}

#pragma mark - ------------ 有深拉效果 ---------------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat y = scrollView.contentOffset.y;
    if (y < -200) {
        CGRect frame = self.headerView.frame;
        
        frame.origin.y = y;
        
        frame.size.height = -y;
        
        self.headerView.frame = frame;
    }
}

#pragma mark - ------------ tap 打开系统手机相册 ---------------
- (void)tapImg:(UITapGestureRecognizer *)tap
{
    
    //创建弹出视图
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
/** 打开相机 */
    UIAlertAction *call = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //判断是否可以打开相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;  //是否可编辑
            //摄像头
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
            [picker release];
        }else{
        
            /** 提示 */
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"Error" message:@"您的设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alertVc addAction:cancel];
           [self presentViewController:alertVc animated:YES completion:nil];
        }
    }];
    
/** 打开系统相册 */
    UIAlertAction *message = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        //签代理
        picker.delegate = self;
        //允许可点击照片并编辑
        picker.allowsEditing = YES;
        
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //转场动画
        picker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        //模态推出
        [self presentViewController:picker animated:YES completion:^{
            
        }];
        
        [picker release];

        
    }];

/** 取消 */
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertVc addAction:call];
    [alertVc addAction:message];
    [alertVc addAction:cancel];
    [self presentViewController:alertVc animated:YES completion:nil];

}

#pragma mark - ------------ UIImagePickerControllerDelegate 编辑完走的方法 要存编辑过的图片 ---------------
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //保存编辑后的照片
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    
    /**< 如果不为空时,就设为选择后图片 */
    if (img != nil) {
        _imgHeader.image = img;
    }
    
    
   //要保存到沙盒里 下一次打开还会显示  图片转成data类型来保存
     NSData *data;
    //要判断图片是什么类型 就两种
    if (UIImagePNGRepresentation(img)) {
        
        data = UIImagePNGRepresentation(img);
    }else{
    
        data = UIImageJPEGRepresentation(img, 1.0);
    }

    /** 存沙盒 */
    [[NSFileManager defaultManager]createFileAtPath:_imgPath contents:data attributes:nil];
    
    //保存
    NSUserDefaults *usetFaults = [NSUserDefaults standardUserDefaults];
    [usetFaults setObject:data forKey:@"img"];
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}



#pragma mark - ------------ 创建Tableview ---------------
- (void)createTableView
{
    
    self.tableView = [[BaseTableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
    _tableView.contentInset = UIEdgeInsetsMake(200, 0, 0, 0);
    [self.view addSubview:_tableView];
/** 夜间 */
    _tableView.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:0.94 green:0.94 blue:0.95 alpha:1.00],[UIColor grayColor]);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"pool"];
    
    [_tableView release];
}


#pragma mark - ------------ 返回row个数 ---------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 4;
    }else if (section == 1){
    
        return 2;
    
    } else{
    
        return 1;
    }
   
}

#pragma mark - ------------ 返回3个分区 ---------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 3;
}

#pragma mark - ------------ cell赋值 ---------------

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
   /** 夜间 */
    cell.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor],[UIColor grayColor]);
   cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
  
/** 夜间 */
    cell.textLabel.dk_textColorPicker = DKColorWithColors([UIColor blackColor],[UIColor lightGrayColor]);
   
    if (indexPath.section == 0) {

        NSArray *arr = [NSArray arrayWithObjects:@"bc", @"bp", @"bn", @"bd",nil];
        cell.imageView.image = [UIImage imageNamed:arr[indexPath.row]];
        switch (indexPath.row) {
/** 我的收藏 */
            case 0:
            {
                cell.textLabel.text = @"我的收藏";
                break;
            }
/** 本地通知 */
            case 1:
            {
                cell.textLabel.text = @"本地通知";
                //取消选中效果
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                BOOL isPush = [[NSUserDefaults standardUserDefaults] boolForKey:@"isPush"];
                
                UISwitch *sw = [[UISwitch alloc]initWithFrame:CGRectZero];
                cell.accessoryView = sw;
                sw.on = isPush;
                [sw addTarget:self action:@selector(switchPost:) forControlEvents:UIControlEventValueChanged];
                [sw release];
                break;
            }
/** 夜间模式 */
            case 2:
            {
                cell.textLabel.text = @"夜间模式";
                //取消选中效果
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                NSString *night = [[NSUserDefaults standardUserDefaults] objectForKey:@"night"];
                UISwitch *sw = [[UISwitch alloc]initWithFrame:CGRectZero];
                cell.accessoryView = sw;
                
                //判断sw开关状态 如果黑天 开关是开启
                if ([night isEqualToString:@"yes"]) {
                    sw.on = YES;
                }else{
                    sw.on = NO;
                }
                
                [sw addTarget:self action:@selector(switchNight:) forControlEvents:UIControlEventValueChanged];
                [sw release];
                break;
            }
/** 清除缓存 */
            case 3:
           {
                cell.textLabel.text = @"清除缓存";
                UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
                img.image = [UIImage imageNamed:@"clear"];
                cell.accessoryView = img;
               [img release];
                break;
            }
            default:
            break;
          
        }
        
    }else if (indexPath.section == 1){
        
        NSArray *arr = [NSArray arrayWithObjects:@"bf", @"be",nil];
        cell.imageView.image = [UIImage imageNamed:arr[indexPath.row]];
        if (indexPath.row == 0) {
            cell.textLabel.text = @"分享给好友";
        }else
        {
            cell.textLabel.text = @"帮助与反馈";
        }
       
    }else{
         cell.imageView.image = [UIImage imageNamed:@"bg"];
         cell.textLabel.text = @"关于";
    }
    return cell;
}


#pragma mark - ------------ 夜间模式 ---------------
- (void)switchNight:(UISwitch *)sw
{
    DKNightVersionManager *manager = [DKNightVersionManager sharedNightVersionManager];
   
    /** 夜间  DKThemeVersionNormal、DKThemeVersionNight 两种状态 */
    if (manager.themeVersion == DKThemeVersionNight) {
        
        [DKNightVersionManager dawnComing];
        [[NSUserDefaults standardUserDefaults]setObject:@"no" forKey:@"Night"];
    }else{
    //白天
        [DKNightVersionManager nightFalling];
        [[NSUserDefaults standardUserDefaults]setObject:@"yes" forKey:@"Night"];
    }
}


#pragma mark - ------------ 本地通知 ---------------
- (void)switchPost:(UISwitch *)sw
{
    if (sw.isOn) {
//推送
       /** 创建一个本地推送 */
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isPush"];
        UILocalNotification *notification = [[[UILocalNotification alloc]init]autorelease];
        //设置两秒之后
        NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:10];
        if (notification != nil) {
            //设置推送时间
            notification.fireDate = pushDate;
            //设置时区
            notification.timeZone = [NSTimeZone defaultTimeZone];
            //设置重复间隔 每日
            notification.repeatInterval = kCFCalendarUnitDay;
            //推送声音
            notification.soundName = UILocalNotificationDefaultSoundName;
            //推送内容
            notification.alertBody = @"是不是无聊?快来交感找找灵感";
            //显示在icon上的红色圈子的数字
            notification.applicationIconBadgeNumber = 1;
            //设置 方便以后撤销之后使用
            NSDictionary *userDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
            notification.userInfo = userDic;
            
            //ios8 之后需要注册 才可授权
            if ([[UIApplication sharedApplication ] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
                
                UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
                UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
                [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            }
            //添加推送到UIApplication
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
            
        }

    }else{
//取消推送
        
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isPush"];
        //获取 UIApplication
        UIApplication *app = [UIApplication sharedApplication];
        //获取本地推送数组
        NSArray *arrLocal = [app scheduledLocalNotifications];
        //声明本地通知对象
        UILocalNotification *localNotification = nil;
        if (arrLocal) {
            
            for (UILocalNotification *noti in arrLocal) {
                NSDictionary *dicNoti = noti.userInfo;
                if (dicNoti) {
                    NSString *inkey = [dicNoti objectForKey:@"key"];
                    if ([inkey isEqualToString:@"name"]) {
                        
                        if (localNotification) {
                            [localNotification release];
                            localNotification = nil;
                        }
                        localNotification = [noti retain];
                        break;
                        
                    }
            }
        }
        if (!localNotification) {
            //判断是否找到已经存在的相同key推送
            localNotification = [[UILocalNotification alloc]init];
            
        }
        if (localNotification) {
            //不推送 取消推送
            [app cancelLocalNotification:localNotification];
            [localNotification release];
            return;
          }
      
       }
    }
}



#pragma mark - ------------ 点击 tableView ---------------
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
        switch (indexPath.row) {
/** 我的收藏 */
            case 0:
            {
                CollectionViewController *collect = [[CollectionViewController alloc]init];
                
                [self.navigationController pushViewController:collect animated:YES];
                [collect release];
                
                break;
            }
/** 清除缓存 */
            case 3:{
                
                [self cleanMeomory];
                break;
            }
            default:
                break;
                
        }
    }else if (indexPath.section == 1){
        
 /** 分享给好友 */
    if (indexPath.row == 0) {
       
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleAlert];
     
        UIAlertAction *call = [UIAlertAction actionWithTitle:@"打电话给好友" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
         
            NSURL *url = [NSURL URLWithString:@"tel://10086"];
            [[UIApplication sharedApplication] openURL:url];
            
        }];
        
        UIAlertAction *message = [UIAlertAction actionWithTitle:@"发短信给好友" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
           
            NSURL *url = [NSURL URLWithString:@"sms://10086"];
            [[UIApplication sharedApplication] openURL:url];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消分享" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertVc addAction:call];
        [alertVc addAction:message];
        [alertVc addAction:cancel];
        [self presentViewController:alertVc animated:YES completion:nil];

    }else{
 /** 帮助与反馈 */
        [self activeMail];
      
        }
    }
/** 关于 */
    else{
        
        AboutViewController *about = [[AboutViewController alloc]init];
        
        about.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        
        [self presentViewController:about animated:YES completion:nil];
        [about release];
      
    }
}



#pragma mark - ------------ 清除缓存 ---------------
- (void)cleanMeomory
{
    //创建管理器对象
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取沙盒
    NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    if ([fileManager fileExistsAtPath:caches]) {
        NSArray *file = [fileManager subpathsAtPath:caches];
        
        //遍历所有文件
        for (NSInteger i = 0; i < file.count; i++) {
            NSString *filePath = [caches stringByAppendingPathComponent:file[i]];
            //获取文件大小
            CGFloat sizeFile = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
            self.cache += sizeFile;
        }
    }
    
    NSString *message = [NSString stringWithFormat:@"是否确认清除%2.1lfM内存?", self.cache / 1024 / 1024];
    
    //判断设备系统是否大于8.0
    if ([[[UIDevice currentDevice]systemVersion] floatValue] > 8.0) {
        
        //提示是否清楚缓存
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cacel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"取消成功");
        }];
        
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            //清除caches文件夹
            NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
            NSFileManager *fileManager = [NSFileManager defaultManager];
            
            if ([fileManager fileExistsAtPath:path]) {
                
                NSArray *fileArray = [fileManager subpathsAtPath:path];
                
                for (NSString *fileName in fileArray) {
                    NSString *cachePath = [path stringByAppendingPathComponent:fileName];
                    [fileManager removeItemAtPath:cachePath error:nil];
                }
            }
            //将缓存值置为0
            self.cache = 0;
            
        }];
        
        [alertView addAction:cacel];
        [alertView addAction:ok];
        [self presentViewController:alertView animated:YES completion:nil];
        
    }else{
        
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:nil message:@"系统版本过低无法清除缓存,请升级系统" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertView animated:YES completion:nil];
        //自动收回
        [self performSelector:@selector(autoBackHome:) withObject:alertView afterDelay:1.5];
    }


}


#pragma mark - ------------ 返回高度 ---------------
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 44;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 10;
}





#pragma mark - ------------ 激活邮件功能 ---------------
- (void)activeMail
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (!mailClass) {

        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前系统版本不支持应用内发送邮件功能，您可以使用mailto方法代替" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertView animated:YES completion:nil];
        //自动收回
        [self performSelector:@selector(autoBackHome:) withObject:alertView afterDelay:1.5];

        return;
    }
    if (![mailClass canSendMail]) {
   
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"用户没有设置邮件账户" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertView animated:YES completion:nil];
        //自动收回
        [self performSelector:@selector(autoBackHome:) withObject:alertView afterDelay:1.5];
        return;
    }
    [self creatPostMail];
}


#pragma mark - ------------ 发送邮件 ---------------
- (void)creatPostMail
{
    
    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc]init];
    
    mailPicker.mailComposeDelegate = self;
    
    //设置主题
    [mailPicker setSubject:@"意见反馈"];
    
    //添加收件人
    [mailPicker setToRecipients:@[@"1172410999@qq.com"]];
    
    //添加抄送
    [mailPicker setCcRecipients: @[@"13109807227@163.com"]];
    
  
    
    //邮件主题
    [mailPicker setMessageBody:@"交感的每一个进步, 都离不开您的意见和建议" isHTML:YES];
    
    
    [self presentViewController:mailPicker animated:YES completion:^{
        
    }];
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    
    NSString *msg;
    
    switch (result) {
        case MFMailComposeResultCancelled:
            msg = @"用户取消编辑邮件";
            break;
            
        case MFMailComposeResultSaved:
            msg = @"用户成功保存邮件";
            break;
            
        case MFMailComposeResultSent:
            msg = @"用户已点击发送, 邮件即将进入待发送状态";
            break;
            
        case MFMailComposeResultFailed:
            msg = @"用户保存或发送邮件失败";
            break;
            
        default:
            msg = @"";
            break;
    }
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    
}



#pragma mark - ------------ alert自动收回 ---------------
- (void)autoBackHome:(UIAlertController *)alert
{

    [alert dismissViewControllerAnimated:YES completion:nil];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
